package com.yueyang.sojourn.server.service.sojourn.merch;

import com.alibaba.fastjson.JSON;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.dto.AddMerchDto;
import com.yueyang.sojourn.server.model.dto.EditMerchDto;
import com.yueyang.sojourn.server.model.enums.ShelfStatusEnum;
import com.yueyang.sojourn.server.model.enums.StatusEnum;
import com.yueyang.sojourn.server.model.po.AttachDetail;
import com.yueyang.sojourn.server.model.po.SojournMerch;
import com.yueyang.sojourn.server.model.po.SojournMerchPic;
import com.yueyang.sojourn.server.model.po.SojournProject;
import com.yueyang.sojourn.server.service.attachdetail.AttachDetailService;
import com.yueyang.sojourn.server.service.sojourn.merch.inventory.MerchInventoryService;
import com.yueyang.sojourn.server.service.sojourn.merchpic.SojournMerchPicService;
import com.yueyang.sojourn.server.service.sojourn.project.SojournProjectService;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yemingxing
 * @summary 写 service
 * @Copyright (c) 2020, Yueyang Group All Rights Reserved.
 * @since 2020-02-17
 */
@Service
public class WriteMerchService {

    @Autowired
    private SojournMerchService sojournMerchService;
    @Autowired
    private SojournMerchPicService sojournMerchPicService;
    @Autowired
    private AttachDetailService attachDetailService;
    @Autowired
    private SojournProjectService sojournProjectService;
    @Autowired
    private MerchInventoryService merchInventoryService;

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public Long addMerch(long loginUserId, AddMerchDto merchDto) {
        SojournProject project = sojournProjectService.selectByPrimaryKey(merchDto.getProjectId());
        if (Objects.isNull(project)) {
            JAssert.justFailed("不存在的所属项目id：" + merchDto.getProjectId());
        }

        SojournMerch sojournMerch = new SojournMerch();
        BeanUtils.copyProperties(merchDto, sojournMerch);

        // todo-ymx 富文本存储，格式转换
        sojournMerch.setTravelRoute(merchDto.getTravelRoute());
        sojournMerch.setDesc(merchDto.getDesc());
        sojournMerch.setPayNotice(merchDto.getPayNotice());
        sojournMerch.setAvailableDateBegin(DateUtils.parseDate(merchDto.getAvailableDateBegin(), "yyyy-MM-dd"));
        sojournMerch.setAvailableDateEnd(DateUtils.parseDate(merchDto.getAvailableDateEnd(), "yyyy-MM-dd"));
        sojournMerch.setDays(merchDto.getDays());
        sojournMerch.setNights(merchDto.getNights());
        sojournMerch.setInventory(merchDto.getInventory());
        sojournMerch.setSale(JSON.toJSONString(merchDto.getSales()));
        sojournMerch.setShelfStatus(ShelfStatusEnum.TO_BE_ON.getCode());
        sojournMerch.setStatus(StatusEnum.VALID.getCode());
        Date nowDate = new Date();
        sojournMerch.setCreator(loginUserId);
        sojournMerch.setCreatedTime(nowDate);
        sojournMerch.setUpdator(loginUserId);
        sojournMerch.setUpdatedTime(nowDate);
        sojournMerchService.insert(sojournMerch);

        merchInventoryService.initInventory(sojournMerch);

        //商品图片
        List<AttachDetail> othersPic = merchDto.getMerchPic().stream().map(attachDto -> {
            AttachDetail attachDetail = new AttachDetail();
            BeanUtils.copyProperties(attachDto, attachDetail);
            attachDetail.setStatus(StatusEnum.VALID.getCode());
            attachDetail.setCreator(loginUserId);
            attachDetail.setCreatedTime(new Date());
            return attachDetail;
        }).collect(Collectors.toList());
        attachDetailService.insertList(othersPic);
        List<SojournMerchPic> projectPics = formatSojournMerchPics(loginUserId, sojournMerch, nowDate, othersPic);
        sojournMerchPicService.insertList(projectPics);
        return sojournMerch.getId();
    }

    private List<SojournMerchPic> formatSojournMerchPics(long loginUserId, SojournMerch merch, Date nowDate, List<AttachDetail> othersPic) {
        return othersPic.stream().map(attachDetail -> {
            SojournMerchPic merchPic = new SojournMerchPic();
            merchPic.setAttachId(attachDetail.getId());
            merchPic.setMerchId(merch.getId());
            merchPic.setStatus(StatusEnum.VALID.getCode());
            merchPic.setCreator(loginUserId);
            merchPic.setCreatedTime(nowDate);
            merchPic.setUpdator(loginUserId);
            merchPic.setUpdatedTime(nowDate);
            return merchPic;
        }).collect(Collectors.toList());
    }

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public void editMerch(long loginUserId, EditMerchDto merchDto) {
        SojournMerch merchBefore = sojournMerchService.selectByPrimaryKey(merchDto.getId());
        if (Objects.isNull(merchBefore)) {
            JAssert.justFailed("不存在的商品id：" + merchDto.getId());
        }

        if (Objects.nonNull(merchDto.getProjectId())) {
            SojournProject project = sojournProjectService.selectByPrimaryKey(merchDto.getProjectId());
            if (Objects.isNull(project)) {
                JAssert.justFailed("不存在的所属项目id：" + merchDto.getProjectId());
            }
        }

        SojournMerch sojournMerch = new SojournMerch();
        BeanUtils.copyProperties(merchDto, sojournMerch);

        // todo-ymx 富文本存储，格式转换
        sojournMerch.setTravelRoute(merchDto.getTravelRoute());
        sojournMerch.setDesc(merchDto.getDesc());
        sojournMerch.setPayNotice(merchDto.getPayNotice());
        sojournMerch.setAvailableDateBegin(Objects.isNull(merchDto.getAvailableDateBegin()) ? null : DateUtils.parseDate(merchDto.getAvailableDateBegin(), "yyyy-MM-dd"));
        sojournMerch.setAvailableDateEnd(Objects.isNull(merchDto.getAvailableDateEnd()) ? null : DateUtils.parseDate(merchDto.getAvailableDateEnd(), "yyyy-MM-dd"));
        sojournMerch.setDays(merchDto.getDays());
        sojournMerch.setNights(merchDto.getNights());
        sojournMerch.setInventory(merchDto.getInventory());
        sojournMerch.setSale(JSON.toJSONString(ListUtils.emptyIfNull(merchDto.getSales())));
        sojournMerch.setShelfStatus(merchDto.getShelfStatus());
        Date nowDate = new Date();
        sojournMerch.setUpdator(loginUserId);
        sojournMerch.setUpdatedTime(nowDate);
        sojournMerchService.updateByPrimaryKeySelective(sojournMerch);

        merchInventoryService.updateMerchInventories(merchBefore, sojournMerch);

        //商品图片
        if (CollectionUtils.isNotEmpty(merchDto.getMerchPic())) {
            List<AttachDetail> merchPic = merchDto.getMerchPic().stream().map(attachDto -> {
                AttachDetail attachDetail = new AttachDetail();
                BeanUtils.copyProperties(attachDto, attachDetail);
                attachDetail.setStatus(StatusEnum.VALID.getCode());
                attachDetail.setCreator(loginUserId);
                attachDetail.setCreatedTime(new Date());
                return attachDetail;
            }).collect(Collectors.toList());
            attachDetailService.insertList(merchPic);

            sojournMerchPicService.invalidByProjectId(loginUserId, merchDto.getId());

            List<SojournMerchPic> projectPics = formatSojournMerchPics(loginUserId, sojournMerch, nowDate, merchPic);
            sojournMerchPicService.insertList(projectPics);
        }
    }

    public void editShelfStatus(long loginUserId, Long merchId, Integer shelfStatus) {
        if (Objects.isNull(ShelfStatusEnum.ofCode(shelfStatus))) {
            JAssert.justFailed("shelfStatus枚举值错误");
        }
        if (ShelfStatusEnum.BEING_ON.getCode() == shelfStatus) {
            SojournMerch sojournMerch = sojournMerchService.selectByPrimaryKey(merchId);
            if (Objects.isNull(sojournMerch)) {
                JAssert.justFailed("商品不存在");
            } else {
                if (DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH).after(sojournMerch.getAvailableDateEnd())) {
                    JAssert.justFailed("当前商品已过期，请调整可出行日期");
                }
            }
        }
        SojournMerch sojournMerch = new SojournMerch();
        sojournMerch.setId(merchId);
        sojournMerch.setUpdator(loginUserId);
        sojournMerch.setUpdatedTime(new Date());
        sojournMerch.setShelfStatus(shelfStatus);
        sojournMerchService.updateByPrimaryKeySelective(sojournMerch);
    }

    public void deleteMerch(long loginUserId, Long merchId) {
        SojournMerch sojournMerch = new SojournMerch();
        sojournMerch.setId(merchId);
        sojournMerch.setUpdator(loginUserId);
        sojournMerch.setUpdatedTime(new Date());
        sojournMerch.setStatus(StatusEnum.INVALID.getCode());
        sojournMerchService.updateByPrimaryKeySelective(sojournMerch);
    }
}
